<template>
  <el-dialog
    append-to-body
    :close-on-click-modal="false"
    :visible.sync="dialogFormVisible"
    :before-close="close"
    :title="title"
    width="800px"
    :top="'10vh'"
  >
    <div style="margin: 15px 0;" />
    <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
      <el-checkbox v-for="item in servicesList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="close">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save('form')">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { queryAllService, queryAllSpecialService, saveAllSpecialService } from '@/api/special/index';
export default {
  name: 'SpecialService',
  data() {
    return {
      dialogFormVisible: false,
      title: '关联服务',
      checkAll: false,
      checkedCities: [],
      form: {},
      rules: {},
      servicesList: [],
      loading: false
    };
  },
  methods: {
    openEntity(data) {
      if (undefined !== data && data !== null && undefined !== data.id && data.id !== null) {
        this.form.special = data;
        this.initAllService();
        this.initChickService();
        this.dialogFormVisible = true;
      } else {
        this.$message.error('未选择关联的专项服务！');
      }
    },
    initChickService() {
      queryAllSpecialService({ sid: this.form.special.id }).then((res) => {
        const { data } = res;
        if (data !== null && undefined !== data && data.length > 0) {
          const ids = data.map(obj => {
            return obj.serviceId;
          });
          this.checkedCities = ids;
        }
      });
    },
    initAllService() {
      queryAllService().then((res) => {
        const { data } = res;
        this.servicesList = data;
      }).catch(() => {
        console.log('初始化服务数据失败！');
      });
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.servicesList.length;
    },
    save() {
      this.loading = true;
      this.form.serviceId = this.checkedCities;
      saveAllSpecialService(this.form).then(res => {
        this.loading = false;
        this.$message.success('保存成功！');
        this.close();
      }).catch(() => {
        this.loading = false;
        this.$message.error('保存失败！');
      });
    },
    close() {
      this.dialogFormVisible = false;
      this.form.special = {};
      this.checkedCities = [];
      this.$emit('fetch-data');
    }
  }
};
</script>

<style scoped>

</style>
